package Windows;

import java.awt.EventQueue;

import Config.Config;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import Util.DatabaseConnection;

import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.SwingConstants;

import net.sf.json.JSONObject;
import Util.ExternalProgramUtil;

import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ConfigWindow {

	private JFrame frmZjoj;
	private JTextField dburl;
	private JTextField username;
	private JPasswordField password;
	private JTextField filepath;
	private static String[] s;
	private JTextField os;
	private JTextField CompileWaitTime;
	private JTextField SearchRate;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		s=args;
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ConfigWindow window = new ConfigWindow();
					window.frmZjoj.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ConfigWindow() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmZjoj = new JFrame();
		frmZjoj.setTitle("ZJOJ评测核心配置窗体");
		frmZjoj.setBounds(100, 100, 570, 325);
		if(s.length==1)
			frmZjoj.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		else
			frmZjoj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmZjoj.getContentPane().setLayout(null);
		
		JLabel label = new JLabel("连接地址:");
		label.setBounds(12, 12, 61, 17);
		frmZjoj.getContentPane().add(label);
		
		dburl = new JTextField();
		dburl.setToolTipText("jdbc:mysql://<ip-address>:[host]/<databasename>");
		dburl.setBounds(88, 12, 350, 21);
		frmZjoj.getContentPane().add(dburl);
		dburl.setColumns(10);
		dburl.setText(Config.dburl);
		
		JLabel label_1 = new JLabel("用户名:");
		label_1.setBounds(12, 42, 61, 17);
		frmZjoj.getContentPane().add(label_1);
		
		username = new JTextField();
		username.setToolTipText("最好是root用户");
		username.setColumns(10);
		username.setBounds(88, 42, 350, 21);
		frmZjoj.getContentPane().add(username);
		username.setText(Config.dbusername);
		
		JLabel label_2 = new JLabel("连接密码:");
		label_2.setBounds(12, 73, 61, 17);
		frmZjoj.getContentPane().add(label_2);
		
		password = new JPasswordField();
		password.setToolTipText("与用户对应的密码");
		password.setBounds(88, 73, 350, 21);
		frmZjoj.getContentPane().add(password);
		password.setText(Config.dbpassword);
		
		filepath = new JTextField();
		filepath.setToolTipText("\u6C38\u4E45\u5B58\u50A8\u914D\u7F6E\u4FE1\u606F\u7684\u4F4D\u7F6E");
		filepath.setColumns(10);
		filepath.setBounds(88, 104, 280, 21);
		frmZjoj.getContentPane().add(filepath);
		filepath.setText(Config.path);
		
		JButton btnNewButton = new JButton("设置(重启核心后生效)");
		
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DatabaseConnection.setInfo(dburl.getText(), username.getText(), password.getText());
				Config.dburl=dburl.getText();
				Config.dbusername=username.getText();
				Config.dbpassword=password.getText();
				Config.path=filepath.getText();
				Config.SearchRate=Integer.parseInt(SearchRate.getText());
				try {
					Config.CompileWaitTime=Integer.parseInt(CompileWaitTime.getText());
				} catch (Exception e2) {
					JOptionPane.showMessageDialog(frmZjoj, "你没有在CompileWaitTime输入一个数值。");
					return ;
				}
				String s="";
				String system=Config.getSystem();
				if(system.length()>=7) {s="\\"; Config.systemPI="\\";} else {s="/"; Config.systemPI="/";};
				Config.systemPI=s;
				frmZjoj.hide();
			}
		});
		btnNewButton.setBounds(199, 249, 161, 27);
		frmZjoj.getContentPane().add(btnNewButton);
		
		final JLabel data_state = new JLabel("未测试连接");
		data_state.setBackground(Color.WHITE);
		data_state.setVerticalAlignment(SwingConstants.TOP);
		data_state.setBounds(448, 42, 99, 17);
		frmZjoj.getContentPane().add(data_state);
		
		JButton btnNewButton_1 = new JButton("测试连接");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DatabaseConnection.setInfo(dburl.getText(), username.getText(), password.getText());
				String DatabaseResult=DatabaseConnection.reSet();
				if(DatabaseResult.equals("")==true){
					data_state.setForeground(Color.GREEN);
					data_state.setText("连接成功！");
				}else{
					data_state.setForeground(Color.RED);
					data_state.setText("连接失败！");
				}
			}
		});
		btnNewButton_1.setBounds(448, 7, 100, 27);
		frmZjoj.getContentPane().add(btnNewButton_1);
		
		JLabel lblNewLabel = new JLabel("文件缓存：");
		lblNewLabel.setBounds(12, 102, 73, 17);
		frmZjoj.getContentPane().add(lblNewLabel);
		
		final JLabel path_state = new JLabel("未选择目录");
		path_state.setVerticalAlignment(SwingConstants.TOP);
		path_state.setBackground(Color.WHITE);
		path_state.setBounds(448, 107, 99, 17);
		frmZjoj.getContentPane().add(path_state);
		
		
		JButton btnNewButton_2 = new JButton("永久存储");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String system=Config.getSystem();
				String s=filepath.getText();
				if(system.length()>=7) s+="\\ZJOJConfig.json"; else s+="/ZJOJConfig.json";
				File f1=new File(s);
				File f2=new File(filepath.getText());
				if(f1.exists()==true){
					f1.delete();
				}
				FileWriter fw=null;
				try {
					if(f2.exists()==false) f2.mkdir();
					f1.createNewFile();
					fw=new FileWriter(f1);
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(frmZjoj, "无法创建文件，详细信息：\n"+e1.toString());
					path_state.setForeground(Color.RED);
					path_state.setText("写入失败");
					return ;
				}
				JSONObject jo=new JSONObject();
				jo.put("dburl", dburl.getText());
				jo.put("dbusername", username.getText());
				jo.put("dbpassword", password.getText());
				jo.put("path", filepath.getText());
				jo.put("OS", system);
				jo.put("CompileWaitTime", CompileWaitTime.getText());
				jo.put("SearchRate", SearchRate.getText());
				String file_content=jo.toString();
				try {
					fw.write(file_content);
					fw.close();
					path_state.setForeground(Color.GREEN);
					path_state.setText("写入成功");
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(frmZjoj, "无法写入文件，详细信息：\n"+e1);
					path_state.setForeground(Color.RED);
					path_state.setText("写入失败");
					return ;
					
				}
			}
		});
		btnNewButton_2.setBounds(448, 68, 100, 27);
		frmZjoj.getContentPane().add(btnNewButton_2);
		
		JButton btnNewButton_3 = new JButton("...");
		btnNewButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fc=new JFileChooser();
				fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			    int result=fc.showDialog(frmZjoj, "选择文件夹");
	            if(result==JFileChooser.APPROVE_OPTION)
	            {
	                String path=fc.getSelectedFile().getPath();
	                filepath.setText(path);
	            }
			}
		});
		btnNewButton_3.setBounds(377, 104, 61, 21);
		frmZjoj.getContentPane().add(btnNewButton_3);
		
		JButton button_1 = new JButton("载入配置文件");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(frmZjoj, "请注意：配置文件是一个任意文件扩展名的文件，它通常位于测评缓存文件夹下，内部存储\n的是一段JSON格式的文本。如果您采用的是自动创建，则这个文件名为ZJOJConfig.json！");
				JFileChooser fc=new JFileChooser();
				fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
			    int result=fc.showDialog(frmZjoj, "选择配置文件");
	            if(result==JFileChooser.APPROVE_OPTION)
	            {
	                String path=fc.getSelectedFile().getPath();
	                File f1=new File(path);
	                String s="";
	                try {
						FileReader fr=new FileReader(f1);
						char[] cbuf=new char[512];
						fr.read(cbuf);
						s=new String(cbuf);
						JSONObject jo=JSONObject.fromObject(s);
						dburl.setText(jo.getString("dburl"));
						username.setText(jo.getString("dbusername"));
						password.setText(jo.getString("dbpassword"));
						filepath.setText(jo.getString("path"));
						CompileWaitTime.setText(jo.getString("CompileWaitTime"));
						SearchRate.setText(jo.getString("SearchRate"));
						if(jo.getString("OS").equals(Config.getSystem())==false) JOptionPane.showMessageDialog(frmZjoj, "特别注意：本配置是来自不同操作系统的计算机的，源计算机的操作系统是：\n"+jo.getString("OS")+"\n，不同的操作系统下的配置共享可能出现问题，请小心使用！");
						path_state.setForeground(Color.GREEN);
						path_state.setText("读取成功");
	                } catch (Exception e1) {
						JOptionPane.showMessageDialog(frmZjoj, "无法使用文件读取流，详细信息：\n"+e1);
						path_state.setForeground(Color.RED);
						path_state.setText("读取失败");
						return ;
					}
	            }
			}
		});
		button_1.setBounds(12, 249, 161, 27);
		frmZjoj.getContentPane().add(button_1);
		
		JLabel label_3 = new JLabel("操作系统：");
		label_3.setBounds(12, 131, 73, 17);
		frmZjoj.getContentPane().add(label_3);
		
		os = new JTextField();
		os.setEditable(false);
		os.setToolTipText("当前操作系统");
		os.setText(Config.getSystem());
		os.setColumns(10);
		os.setBounds(88, 131, 350, 21);
		frmZjoj.getContentPane().add(os);
		
		JLabel label_4 = new JLabel("编译等待时间：");
		label_4.setBounds(12, 158, 105, 17);
		frmZjoj.getContentPane().add(label_4);
		
		CompileWaitTime = new JTextField();
		CompileWaitTime.setToolTipText("CompileWaitTime（ms）");
		CompileWaitTime.setText("");
		CompileWaitTime.setColumns(10);
		CompileWaitTime.setBounds(98, 158, 73, 21);
		frmZjoj.getContentPane().add(CompileWaitTime);
		
		JLabel label_5 = new JLabel("\u6570\u636E\u5E93\u626B\u63CF\u9891\u7387\uFF1A");
		label_5.setBounds(181, 158, 105, 17);
		frmZjoj.getContentPane().add(label_5);
		
		SearchRate = new JTextField();
		SearchRate.setToolTipText("SearchRate");
		SearchRate.setText("");
		SearchRate.setColumns(10);
		SearchRate.setBounds(275, 158, 73, 21);
		frmZjoj.getContentPane().add(SearchRate);
		
		JButton button = new JButton("\u53D6\u6D88\u8BBE\u7F6E");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(s.length==1)
					frmZjoj.hide();
				else
					System.exit(0);
			}
		});
		button.setBounds(386, 249, 161, 27);
		frmZjoj.getContentPane().add(button);
		
	}
}
